<template>
	<view class="container">
		<tui-navigation-bar :isOpacity="false" :maxOpacity="1" @init="initNavigation" :scrollTop="scrollTop"
			backgroundColor="#fff" color="#333" :title="pageTitle">
			<view class="tui-header" :style="{ marginTop: navBarTop + 'px' }">
				<view class="get-back dy-iconfont icon-qiehuanqizuo" @click="goBack"></view>
			</view>
		</tui-navigation-bar>
		<view class="main" v-if="loding">
			<view class="send-content">
				<uv-textarea v-model="sendValue" placeholder="请填写动态内容" class="uv-textarea-a"
					laceholderStyle="fontSize: 26rpx;fontSeight: 400;color: #999B9B;lineHeight: 37rpx;" border="none"
					height="150" maxlength="500" autoHeight></uv-textarea>
				<view class="add-image-list">
					<uv-upload :fileList="fileList1" name="1" multiple :maxCount="maxCount" :accept="accept"
						@afterRead="afterRead" @delete="deletePic" @error="uploadError" ref="upload">
						<view class="add-image" @tap="selectMedia">
							<uv-icon name="plus" color="#D8D8D8" size="50"></uv-icon>
						</view>
					</uv-upload>
				</view>
				<view class="border-bottom"></view>
				<view class="topic">话题</view>
				<view class="topic-list">
					<tabs @change="onCategory" keyName="categoryName" :list="topicList" type="send">
						<!-- #ifdef MP -->
						<template v-slot:indicator="{content}">
							<view class="title">#{{content.topicName}}</view>
						</template>
						<!-- #endif -->

						<!-- #ifndef MP -->
						<template v-slot:indicator="slotProps">
							<view class="title">#{{slotProps.content.topicName}}</view>
						</template>
						<!-- #endif -->
					</tabs>
				</view>
				<view class="selec-place" @tap.stop.prevent="selectPlace">
					<view class="place">{{location ? location.name : '地点'}}</view>
					<view class="right" :class="{'clear':location}" @tap.stop.prevent="clearLocation(location)"></view>
				</view>
			</view>
		</view>
		<uv-action-sheet ref="actionSheet" round="20" cancelText="关闭" :actions="list" closeOnClickOverlay
			@select="selectMediaItem">
		</uv-action-sheet>
		<button class="btn-primary btn-submit" @tap.stop.prevent="onSubmit">发布</button>
		<survey-pop></survey-pop>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import mp from "@/mixins/mp.js";
	import throttle from '@/uni_modules/uv-ui-tools/libs/function/throttle.js';
	import tabs from '@/uni_modules/uv-tabs/components/uv-tabs/uv-tabs-index.vue';
	import {
		postTextAuditing
	} from '@/utils/requset/check.js';
	const app = getApp();
	export default {
		mixins: [mp],
		options: {
			styleIsolation: 'shared'
		}, //解决/deep/不生效**
		components: {
			tabs
		},
		data() {
			return {
				navBarOpacity: 0, //标题图标距离顶部距离
				scrollTop: 0.5, //页面滚动高度
				navBarTop: 0, // 导航栏content顶部m-top
				pageTitle: '', //标题
				sendValue: '',
				pictureList: [],
				fileList1: [],
				accept: '',
				imgLoding: true,
				video: '',
				maxCount: 1,
				list: [{
					name: '图片',
					lable: 'image'
				}, {
					name: '视频',
					lable: 'video'
				}],
				topicList: [],
				loding: false,
				location: null,
				topic: null,
				submitStart: true,
			};
		},
		/**
		 * 计算属性
		 */
		computed: {
			getCountPicture() {
				return this.pictureList.length;
			},
		},
		onLoad(options) {
			this.requestTopicList().then(() => {
				this.loding = true
			}).catch(() => {
				this.loding = true
			})
		},
		onShow: function() {},
		/**
		 * 下拉
		 */
		onPullDownRefresh: function() {},
		/**
		 * 触底
		 */
		onReachBottom() {},
		/**
		 * 滚动
		 */
		onPageScroll(res) {
			this.scrollTop = res.scrollTop;
		},
		methods: {
			goLogin() {
				app.doLogin()
			},
			initNavigation(e) {
				this.navBarOpacity = e.opacity;
				this.navBarTop = e.top;
			},
			selectMedia() {
				if (this.accept == 'image') {
					this.$refs.upload.chooseFile();
					return
				}
				this.$refs.actionSheet.open();
			},
			selectMediaItem(e) {
				this.maxCount = e.lable == 'image' ? 9 : 1
				this.accept = e.lable
				this.$refs.upload.chooseFile();
			},
			uploadError(e) {
				if (this.fileList1.length == 0) {
					this.accept = ''
				}
			},
			requestTopicList() {
				return new Promise((resolve, reject) => {
					app._get('/client/forum-topic/topic-list', null, (result) => {
						this.topicList = result.data
						resolve()
					}, null, (err) => {
						reject()
					})
				})
			},
			selectPlace() {
				wx.chooseLocation({
					success: (res) => {
						this.location = res
					},
					fail: () => {},
					complete: function() {}
				})
			},
			clearLocation(location) {
				console.log(location);
				if (location) {
					this.location = null
				} else {
					this.selectPlace()
				}
			},
			selectTopic(item) {
				if (!this.topic || this.topic.topicId != item.topicId) {
					this.topic = item
				}
			},
			onCategory(e) {
				if (e.innerCurrent != 999) {
					this.topic = e
				} else {
					this.topic = null
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				// console.log("文件大小",lists);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, lists[i].type)
					// console.log("文件大小", result.size);
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: result ? 'success' : 'failed',
						message: result ? '' : '上传失败',
						url: !result ? '' : result.coverPictureUrl ? result.coverPictureUrl : result.url,
						path: result ? result.path : '',
						type: result ? result.fileType : '',
						fileUrl: result ? result.url : '',
						coverPicturePath: result ? result.coverPicturePath : '',
						videoHeight: result ? result.videoHeight : '',
						videoWidth: result ? result.videoWidth : '',
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, type) {
				return new Promise((resolve, reject) => {
					let header = {}
					if (app.globalData.token) {
						header = {
							token: 'Bearer ' + app.globalData.token,
						}
					}
					let a = uni.uploadFile({
						url: app.globalData.api_root + '/client/file/anyone/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							storageType: 'TENCENT_COS',
							bucket: 'pengtou-1322587508',
							bizType: type == 'video' ? 'video-frame' : 'send'
						},
						header: header || {},
						success: (res) => {
							let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
							app.failCode(result)
							setTimeout(() => {
								this.$refs.toast.hide()
								let time = result.data.coverPictureUrl ? 2000 : 200
								if (0 == result.code || 200 == result.code) {
									setTimeout(() => {
										resolve(result.data)
									}, time)
								} else {
									setTimeout(() => {
										resolve(false);
									}, 200)
								}
							}, 1000)
						},
						fail: (err) => {
							console.log('err', err);
							setTimeout(() => {
								resolve(false);
							}, 1000)
						},
					});
				})
			},
			// 返回上一页
			goBack: function() {
				app.beNavigateBack();
			},
			//文本内容审核  1 资料；2 评论；3 论坛；
			checkMessage(messageContent, scene) {
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/input-check/check-message", {
							messageContent: messageContent,
							scene: scene
						},
						(result) => {
							let res = result.data
							resolve(res);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},
			async onSubmit() {
				let that = this;
				if (!that.submitStart) {
					return
				}
				that.submitStart = false
				// console.log(postTextAuditing(that.sendValue));
				if (!that.sendValue) {
					that.$refs.toast.show({
						type: 'default',
						message: "请填写动态内容"
					})
					setTimeout(() => {
						that.$refs.toast.hide()
					}, 1000)
					that.submitStart = true
					return
				}
				that.$refs.toast.show({
					type: 'loading',
				})
				const check_message = await that.checkMessage(that.sendValue, 3)
				if (!check_message) {
					that.$refs.toast.hide()
					that.submitStart = true
					that.$refs.toast.show({
						type: 'default',
						message: "请勿输入违规内容"
					})
					setTimeout(() => {
						that.$refs.toast.hide()
					}, 1000)
					return
				}
				let sendPictureList = [];
				that.fileList1.forEach((item, index) => {
					sendPictureList.push({
						"coverPictureUrl": item.coverPicturePath,
						"fileUrl": item.path,
						"fileHeight": item.videoHeight,
						"fileWidth": item.videoWidth,
					})
				})
				// console.log(sendPictureList);
				throttle(
					app._post_form("/client/forum/submit", {
							"content": that.sendValue,
							"forumType": 1,
							"recommendState": null,
							"orderId": null,
							"anonymityState": null,
							"pictureList": sendPictureList,
							"forumAddress": that.location ? that.location.name : null,
							"locationLatitude": that.location ? that.location.longitude : null,
							"locationLongitude": that.location ? that.location.latitude : null,
							"topicId": that.topic ? that.topic.topicId : null
						},
						(res) => {
							that.$refs.toast.hide()
							setTimeout(() => {
								that.$refs.toast.show({
									type: 'success',
									message: "提交成功"
								})
								setTimeout(() => {
									that.$refs.toast.hide()
									that.submitStart = true
									app.navigationTo('page_user/post/post')
								}, 1000)
							}, 500)
						}, () => {
							that.submitStart = true
						}, () => {
							that.$refs.toast.hide()
						}), 1000, true)
			},
		},
	};
</script>
<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #F6F8F7;

		.tui-header {
			width: 100%;
			position: fixed;
			top: 0;
			padding: 0 42rpx;
			display: flex;
			align-items: center;
			height: 32px;
			transform: translateZ(0);
			z-index: 99999;
			box-sizing: border-box;

			.get-back {
				flex-shrink: 0;
				width: 36rpx;
				height: 36rpx;
				color: #000;
				font-size: 36rpx;
				padding: 2rpx 40rpx 2rpx 2rpx;
			}
		}

		.main {
			box-sizing: border-box;
			padding: 212rpx 24rpx 66rpx;

			/* #ifdef H5 */
			padding: 124rpx 24rpx 66rpx;
			/* #endif */

			.send-content {
				min-height: 624rpx;
				background: #FFFFFF;
				border-radius: 12rpx;
				box-sizing: border-box;
				padding: 36rpx 28rpx;

				.uv-textarea-a {
					padding: 0;
				}
			}

			.add-image-list {
				display: flex;
				flex-wrap: wrap;
				margin-top: 44rpx;
				margin-bottom: 36rpx;
			}

			.border-bottom {
				width: 100%;
				height: 1rpx;
				background: #E3E9E5;
				margin-bottom: 40rpx;
			}

			.topic {
				font-size: 32rpx;
				font-weight: 900;
				color: #1E1F1F;
				line-height: 45rpx;
				margin-bottom: 24rpx;

				&::before {
					font-family: "dy-iconfont";
					position: relative;
					content: "\e634";
					font-size: 37rpx;
					margin-right: 12rpx;
				}
			}

			/deep/.uv-tabs__wrapper__scroll-view {
				height: auto;

				.uv-tabs__wrapper__nav__item {
					height: 56rpx !important;
					background: #F6F8F7;
					border-radius: 28rpx;
					font-size: 28rpx;
					font-weight: 400;
					color: #999B9B;
					line-height: 56rpx;
					margin-right: 12rpx;
					display: inline-block;
					box-sizing: border-box;
					padding: 0 18rpx;
					top: 0;

					&.active {
						background: #FFFFFF;
						border: 2rpx solid #0E0E0D;
						font-weight: 900;
						color: #282D2D;
					}

					&::before {
						display: none;
					}
				}
			}

			.topic-list {
				margin-bottom: 40rpx;

				.scroll-view-H {
					.topic-item {
						height: 56rpx;
						background: #F6F8F7;
						border-radius: 28rpx;
						font-size: 28rpx;
						font-weight: 400;
						color: #999B9B;
						line-height: 56rpx;
						margin-right: 12rpx;
						display: inline-block;
						box-sizing: border-box;
						padding: 0 18rpx;

						&.topic-item-active {
							background: #FFFFFF;
							border: 2rpx solid #0E0E0D;
							font-weight: 900;
							color: #282D2D;
						}
					}
				}
			}

			.selec-place {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.place {
					font-size: 32rpx;
					font-weight: 900;
					color: #1E1F1F;
					line-height: 45rpx;

					&::before {
						font-family: "dy-iconfont";
						position: relative;
						content: "\e637";
						font-size: 37rpx;
						margin-right: 12rpx;
					}
				}

				.right {
					font-size: 28rpx;
					font-weight: 400;
					color: #282D2D;
					line-height: 40rpx;

					&::after {
						font-family: "dy-iconfont";
						position: relative;
						content: "\e600";
						font-size: 20rpx;
						margin-left: 12rpx;
						line-height: 40rpx;
						top: -2rpx;
						color: #999B9B;
					}

					&.clear {
						&::after {
							font-family: "dy-iconfont";
							position: relative;
							content: "\e61d";
							font-size: 20rpx;
							margin-left: 12rpx;
							line-height: 40rpx;
							top: 2rpx;
							color: #999B9B;
						}
					}
				}
			}

			.add-image {
				width: 190rpx;
				height: 190rpx;
				background: #F6F8F7;
				border-radius: 16rpx;
				border: 2rpx dashed #C4CFCA;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.picture-item {
				position: relative;

				.del-btn {
					position: absolute;
					display: flex;
					top: -10rpx;
					right: -10rpx;
					z-index: 2;
				}
			}

			.picture-item-video {
				margin: 0 auto;
			}

			.picture-item-image {
				width: 190rpx;
				height: 190rpx;
				margin-right: 20rpx;
				margin-bottom: 20rpx;

				.picture-image {
					width: 100%;
					height: 100%;
					border-radius: 10px;
				}
			}
		}

		.btn-submit {
			position: fixed;
			width: calc(100% - 77rpx * 2);
			bottom: calc(constant(safe-area-inset-bottom) + 64rpx);
			bottom: calc(env(safe-area-inset-bottom) + 64rpx);
			left: 50%;
			transform: translateX(-50%);
			z-index: 10;
		}
	}
</style>